package com.baofang.bao.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.baofang.bao.entity.User;
import com.baofang.bao.service.UserServiceImpl;

@Controller		// @RestController = @Controller + @ResponseBody
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserServiceImpl userServiceImpl;
	

	/**
	 * 跳转登录页面
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/logintz")
	public String Longtz() {
		System.out.println("____________跳转登录页面");
		return "login";
	}
	/**
	 * 跳转主页页面
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/indextz")
	public String Indextz(@SessionAttribute(WebSecurityConfig.SESSION_KEY)String userName, Model model) {
		System.out.println("____________跳转主页页面");
		model.addAttribute("user", userName);
		return "index";
	}
	/**
	 * 登录验证
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/login")
	public String Login(String userName,String password,HttpSession session,Model model) {
		System.out.println("username:"+userName);
		System.out.println("username:"+password);
		User u=userServiceImpl.findByUserNameAndPassword(userName, password);
	    System.out.println(u);
	    if(u!=null) {
			session.setAttribute(WebSecurityConfig.SESSION_KEY, userName);
			model.addAttribute("userName", userName);
			return "index";
	       }else {
			   model.addAttribute("cue", "用户名或者密码错误！");
			   return "login";
		      }
		
	}
	/**
	 * 
	 */
	
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		//移除session
		session.removeAttribute(WebSecurityConfig.SESSION_KEY);
		return "login";
	}
	/**
	 * 添加用户
	 * @param username
	 * @param password
	 * @param age
	 * @param tell
	 * @param email
	 * @param headLogoUrl
	 * @return
	 */
	@RequestMapping("/add_user.do")
	public int AddUser(String username,String password,Integer age,String tell,
			String email,String headLogoUrl) {
	if(userServiceImpl.findByUserName(username)!=null) {
		User user=new User();
		user.setAge(age);
		user.setEmail(email);
		user.setHeadLogoUrl(headLogoUrl);
		user.setUserName(username);
		user.setPassword(password);
		user.setTell(tell);
		if(userServiceImpl.saveUser(user)!=null) {
			return  1;
		}else {
			return  0;
		}     		
	}else {
		
	}
	return 0;
	}
	
}
